package com.piece.core.framework.util.schedule;

import com.piece.core.framework.exception.ServerException;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;

/**
 * 定时任务实现类
 */
public class ScheduleRunnable implements Runnable {

    private Object target;

    private Method method;

    private ScheduleJob scheduleJob;

    public ScheduleRunnable(Object target, String methodName, ScheduleJob scheduleJob) throws Exception {
        this.target = target;
        this.scheduleJob = scheduleJob;

        if (null != scheduleJob.getParam()) {
            this.method = target.getClass().getDeclaredMethod(methodName, ScheduleJob.class);
        } else {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }

    @Override
    public void run() {
        try {
            ReflectionUtils.makeAccessible(method);
            if (null != scheduleJob.getParam()) {
                method.invoke(target, scheduleJob);
            } else {
                method.invoke(target);
            }
        } catch (Exception e) {
            throw new ServerException(e.getMessage());
        }
    }
}